<template>
  <div class="permissions-page">
    <div class="page-header">
      <h2>权限管理</h2>
      <el-button type="primary" @click="showAddDialog = true">
        <el-icon><Plus /></el-icon>
        添加权限
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="权限名">
          <el-input v-model="searchForm.name" placeholder="请输入权限名" clearable />
        </el-form-item>
        <el-form-item label="权限代码">
          <el-input v-model="searchForm.code" placeholder="请输入权限代码" clearable />
        </el-form-item>
        <el-form-item label="模块">
          <el-select v-model="searchForm.module" placeholder="请选择模块" clearable>
            <el-option
              v-for="module in modules"
              :key="module"
              :label="module"
              :value="module"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadPermissions">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 权限列表 -->
    <el-card>
      <el-table :data="permissions" v-loading="loading" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="权限名" />
        <el-table-column prop="code" label="权限代码" />
        <el-table-column prop="module" label="模块" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="created_at" label="创建时间">
          <template #default="{ row }">
            {{ formatDateTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="editPermission(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deletePermission(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadPermissions"
          @current-change="loadPermissions"
        />
      </div>
    </el-card>

    <!-- 添加/编辑权限对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingPermission ? '编辑权限' : '添加权限'"
      width="600px"
    >
      <el-form
        ref="permissionFormRef"
        :model="permissionForm"
        :rules="permissionRules"
        label-width="100px"
      >
        <el-form-item label="权限名" prop="name">
          <el-input v-model="permissionForm.name" placeholder="请输入权限名" />
        </el-form-item>
        <el-form-item label="权限代码" prop="code">
          <el-input v-model="permissionForm.code" placeholder="请输入权限代码" />
        </el-form-item>
        <el-form-item label="模块" prop="module">
          <el-select v-model="permissionForm.module" placeholder="请选择模块" style="width: 100%">
            <el-option
              v-for="module in modules"
              :key="module"
              :label="module"
              :value="module"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="permissionForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="savePermission" :loading="saving">
          {{ editingPermission ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { userManagementAPI } from '@/api/userManagement'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const permissions = ref([])

// 对话框控制
const showAddDialog = ref(false)
const editingPermission = ref(null)

// 搜索表单
const searchForm = reactive({
  name: '',
  code: '',
  module: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 权限表单
const permissionForm = reactive({
  name: '',
  code: '',
  module: '',
  description: ''
})

// 表单引用
const permissionFormRef = ref()

// 计算属性
const modules = computed(() => {
  const moduleSet = new Set(permissions.value.map(p => p.module))
  return ['用户管理', 'CMDB管理', 'SQL管理', '系统管理', ...Array.from(moduleSet)]
})

// 表单验证规则
const permissionRules = {
  name: [
    { required: true, message: '请输入权限名', trigger: 'blur' },
    { min: 2, max: 100, message: '权限名长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限代码', trigger: 'blur' },
    { min: 2, max: 100, message: '权限代码长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  module: [
    { required: true, message: '请选择模块', trigger: 'change' }
  ]
}

// 方法
const loadPermissions = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      page_size: pagination.pageSize,
      ...searchForm
    }

    const response = await userManagementAPI.getPermissions(params)
    permissions.value = response.results || response
    pagination.total = response.count || response.length
  } catch (error) {
    console.error('加载权限失败:', error)
    ElMessage.error('加载权限失败')
  } finally {
    loading.value = false
  }
}

const resetSearch = () => {
  searchForm.name = ''
  searchForm.code = ''
  searchForm.module = ''
  pagination.page = 1
  loadPermissions()
}

const editPermission = (permission) => {
  editingPermission.value = permission
  permissionForm.name = permission.name
  permissionForm.code = permission.code
  permissionForm.module = permission.module
  permissionForm.description = permission.description
  showAddDialog.value = true
}

const savePermission = async () => {
  if (!permissionFormRef.value) return

  try {
    await permissionFormRef.value.validate()
    saving.value = true

    if (editingPermission.value) {
      await userManagementAPI.updatePermission(editingPermission.value.id, permissionForm)
      ElMessage.success('权限更新成功')
    } else {
      await userManagementAPI.createPermission(permissionForm)
      ElMessage.success('权限创建成功')
    }

    showAddDialog.value = false
    resetForm()
    loadPermissions()
  } catch (error) {
    console.error('保存权限失败:', error)
    ElMessage.error('保存权限失败')
  } finally {
    saving.value = false
  }
}

const deletePermission = async (permission) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除权限 "${permission.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await userManagementAPI.deletePermission(permission.id)
    ElMessage.success('权限删除成功')
    loadPermissions()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除权限失败:', error)
      ElMessage.error('删除权限失败')
    }
  }
}

const resetForm = () => {
  permissionForm.name = ''
  permissionForm.code = ''
  permissionForm.module = ''
  permissionForm.description = ''
  editingPermission.value = null
  if (permissionFormRef.value) {
    permissionFormRef.value.resetFields()
  }
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadPermissions()
})
</script>

<style scoped>
.permissions-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
